package com.hankol.newretail

import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.MessageBus
import com.baselibrary.bean.ReceiveAddressBean
import com.baselibrary.extension.*
import com.baselibrary.manager.LoadingManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.activity.BaseActivity
import com.hankol.newretail.adapter.ConfrimOrderGoodListMultAdapter
import com.hankol.newretail.bean.AddressData
import com.hankol.newretail.bean.OrderDetailBean
import com.hankol.newretail.bean.RemarkBean
import com.hankol.newretail.databinding.ActivityConfirmOrderNewRetailBinding
import com.hankol.newretail.utils.RetailPopUtils
import com.hankol.newretail.viewmodel.OrderAboutViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**新零售-确认订单
 * @author: merbng
 * @time: 2022/8/5 9:48
 * @description:
 */
@Route(path = ActivityRouter.NEW_RETAIL.CONFIRM_ORDER)
class ConfirmNewRetailOrderActivity : BaseActivity(), View.OnClickListener {
    private lateinit var viewModel: OrderAboutViewModel
    private lateinit var binding: ActivityConfirmOrderNewRetailBinding
    private val mAdapter by lazy { ConfrimOrderGoodListMultAdapter(emptyList()) }
    private var numStr = ""
    private var skuid = ""
    private var cartids = ""
    private var userAddressId = 0
    var mDataBean: OrderDetailBean? = null

    companion object {
        //key 购买数量（从商品详情进入）
        const val KEY_CONFIRM_ORDER_NUM = "num"

        //key skuid（从商品详情进入）
        const val KEY_CONFIRM_ORDER_SKUID = "skuId"

        // cartids（从购物车进入）
        const val KEY_CONFIRM_ORDER_CARTIDS = "cartIds"
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_confirm_order_new_retail
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        binding = getDataBinding()
        //取值
        viewModel = getActivityViewModelProvider(this).get(OrderAboutViewModel::class.java)
        if (ARouterUtils.parseParams(intent.extras!!, KEY_CONFIRM_ORDER_NUM)[0].checkNotNull()) {
            numStr = ARouterUtils.parseParams(intent.extras!!, KEY_CONFIRM_ORDER_NUM)[0]
        }
        if (ARouterUtils.parseParams(intent.extras!!, KEY_CONFIRM_ORDER_SKUID)[0].checkNotNull()) {
            skuid = ARouterUtils.parseParams(intent.extras!!, KEY_CONFIRM_ORDER_SKUID)[0]
        }
        if (ARouterUtils.parseParams(intent.extras!!, KEY_CONFIRM_ORDER_CARTIDS)[0].checkNotNull()) {
            cartids = ARouterUtils.parseParams(intent.extras!!, KEY_CONFIRM_ORDER_CARTIDS)[0]
        }
        initView()
        initListener()
        initObserver()
        requestData()
    }

    private fun initObserver() {
        viewModel.addressDataLD.observe(this, Observer {
            //地址
            if (it.checkNotNull()) {
                if (it.size > 0) {
                    haveAddress(it[0])
                } else {
                    //无地址
                    noAddress()
                }
            } else {
                //无地址
                noAddress()
            }
        })
        //确认订单详情
        viewModel.orderDetailLD.observe(this, Observer {
            if (it.checkNotNull()) {
                setOrderDetail(it)
            }
        })
        //提交订单
        viewModel.commitOrderLD.observe(this, Observer {
            LoadingManager.hideProgress(this)
            if (it.checkNotNull()) {
                EventBusUtils.sendNotify(MessageBus.msgId_commit_order_success)
                if (it.payType == 1) {
                    //不需要支付 直接跳转 支付成功页
                    viewModel.reqCreateScoreOrder(it.poids)
                } else {//跳转收银台
                    val hashMap = java.util.HashMap<String, Any>()
                    hashMap[SelectPayWayActivity.KEY_POIDS] = it.poids.checkValue()
                    hashMap[SelectPayWayActivity.KEY_OVERTIME] = it.overtime
                    hashMap[SelectPayWayActivity.KEY_SHOULD_PAY_PRICE] = it.shouldPayPrice
                    ARouterUtils.jump(ActivityRouter.NEW_RETAIL.SELECT_PAY_WAY, hashMap)
                    AppManager.getAppManager().finishActivity()
                }
            }
        })
        //纯酒币（无现金）_电商订单_生成支付订单
        viewModel.onlyScoreOrderLD.observe(this, Observer {
            EventBusUtils.sendNotify(MessageBus.msgId_pay_success)
            val hashMap = java.util.HashMap<String, Any>()
            hashMap[PaySuccessActivity.KEY_POIDS] = it.poids.checkValue()
            hashMap[PaySuccessActivity.KEY_PAY_PRICE_SUM] = "${it.payPriceSum}"
            hashMap[PaySuccessActivity.KEY_SCORE_DEDUCTPRICE_SUM] = "${it.scoreDeductPriceSum}"
            hashMap[PaySuccessActivity.KEY_SHOULD_REWARD_SCORE] = "${it.shouldRewardScore}"
            ARouterUtils.jump(ActivityRouter.NEW_RETAIL.PAY_SUCCESS, hashMap)
            AppManager.getAppManager().finishActivity()
        })
    }

    private fun setOrderDetail(detailBean: OrderDetailBean?) {
        detailBean?.let {
            mDataBean = it
            mAdapter.setNewData(it.mallOrderShopDtoList)
            //多个店铺，隐藏外层的备注
            binding.llOutRemark.visibility = if (it.mallOrderShopDtoList.size > 1) View.GONE else View.VISIBLE
            //邮费
            binding.tvPostage.text = "¥${AmountUtil.changeF2YKeepTwo("${it.postage}")}"
            //商品总价格/订单总额
            binding.tvPriceSum.text = "¥${AmountUtil.changeF2YKeepTwo("${it.priceSum}")}"
            binding.tvBottomNumSum.text = "共${it.numSum}件｜合计："
            binding.tvBottomTotalPrice.text = "${AmountUtil.changeF2YKeepTwo("${it.priceSum}")}"

            binding.tvCoinTotal.text = "酒币（共${it.scoreInfo.myScore}个）"
            //是否可使用酒币:0可用，1不可用，2不够
            when (it.scoreInfo.scoreStatus) {
                0 -> {
                    binding.tvUseCoin.isEnabled = true
                    binding.tvUseCoin.text = "-¥${AmountUtil.changeF2YKeepTwo("${it.scoreInfo.scoreDeductPrice}")}"
                    binding.tvUseCoin.setTextColor(ContextCompat.getColor(this@ConfirmNewRetailOrderActivity, R.color.color_D53))
                    binding.tvBottomTotalPrice.text = "${AmountUtil.changeF2YKeepTwo("${it.priceSum.minus(it.scoreInfo.scoreDeductPrice)}")}"
                    useScoreStatus = 0
                    binding.imgCoinUseArrow.visibility = View.VISIBLE
                }
                1 -> {
                    binding.tvUseCoin.text = "订单不可使用酒币"
                    binding.tvUseCoin.isEnabled = false
                    binding.tvUseCoin.setTextColor(ContextCompat.getColor(this, R.color.color_D8D8D8))
                    useScoreStatus = 1
                    binding.imgCoinUseArrow.visibility = View.GONE
                }
                2 -> {
                    binding.tvUseCoin.text = "剩余 ${it.scoreInfo.myScore}，满${it.scoreInfo.leastScore}可用"
                    binding.tvUseCoin.isEnabled = false
                    binding.tvUseCoin.setTextColor(ContextCompat.getColor(this, R.color.color_D8D8D8))
                    useScoreStatus = 1
                    binding.imgCoinUseArrow.visibility = View.GONE
                }
            }
            //binding.tvCommitOrder  是否允许提交订单：0否，1是
            binding.tvCommitOrder.setBackgroundResource(if (it.allowSubmit == 1) R.drawable.bg_solid_f54d53_r20 else R.drawable.bg_solid_f54d53_r20_a50)
            binding.llLoading.postDelayed(Runnable {
                //解决华为手机闪一下
                binding.llLoading.visibility = View.GONE
            }, 50)
        }
    }

    private fun requestData() {
        //获取地址
        viewModel.requestAddressList()
        if (cartids.checkNotNull()) {
            viewModel.requestConfirmOrderDetail4Cart(cartids)
        } else {
            viewModel.requestConfirmOrderDetail4GoodsDetail(numStr, skuid)
        }
    }

    private fun initListener() {
        binding.ivBack.setOnClickListener(this)
        binding.tvUseCoin.setOnClickListener(this)
        binding.imgCoinRuler.setOnClickListener(this)
        binding.tvCommitOrder.setOnClickListener(this)
    }

    private fun initView() {
        binding.llLoading.visibility = View.VISIBLE
        mAdapter.setCurrentActivity(this)
        binding.rvConfrimOrderGoods.adapter = mAdapter
        binding.tvBottomTotalPrice.setMallPriceTTF(this)
        binding.imgRemarkArrow.setBackgroundResource(R.drawable.ic_right_arrow_d8d8)
        binding.etRemark.addTextChangedListenerClosure(afterTextChanged = {
            if (it.toString().length == 0) {
                binding.imgRemarkArrow.setBackgroundResource(R.drawable.ic_right_arrow_d8d8)
            } else {
                binding.imgRemarkArrow.setBackgroundResource(R.drawable.ic_right_arrow)
            }
        })
        binding.tvUnit.setMallPriceTTF(this)
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.iv_back -> {
                finish()
            }
            R.id.tv_commit_order -> {
                //提交订单
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    commitOrderHandle()
                }
            }
            R.id.tv_use_coin -> {
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    showUseWineCoin()
                }
            }
            R.id.img_coin_ruler -> {
                //酒币规则
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    coinRuler()
                }
            }
        }
    }

    //使用酒币：0使用，1不使用
    var useScoreStatus = 0

    //提交订单
    private fun commitOrderHandle() {
        //是否允许提交订单：0否，1是
        if (mDataBean?.allowSubmit == 0) return
        if (userAddressId == 0) {
            "请填写收货地址".toast()
            return
        }
        LoadingManager.showProgress(this, "请稍后...")
        var descStr = "[]"
        mDataBean?.let {
            if (it.mallOrderShopDtoList.size > 1) { //多个店铺
                val remarkList = mutableListOf<String>()
                for (mallOrderShopDtoBean in mAdapter.data) {
                    if (mallOrderShopDtoBean.remarkStr.checkNotNull()) {
                        remarkList.add(mallOrderShopDtoBean.remarkStr.checkValue())
                    }
                }
                if (remarkList.size > 0) {
                    descStr = remarkList.toString().checkValue()
                }
            } else {
                val remarkList = mutableListOf<String>()
                remarkList.add(CommonUtil.beanToJson(RemarkBean(it.mallOrderShopDtoList[0].shopId, binding.etRemark.text.toString().checkValue())))
                descStr = remarkList.toString().checkValue()
            }
        }
        if (cartids.checkNotNull()) {
            //从购物车
            viewModel.reqCommitOrder4Cart(cartids, useScoreStatus, userAddressId, descStr)
        } else {
            //从商品详情
            viewModel.reqCommitOrder4GoodsDetail(numStr, skuid, useScoreStatus, userAddressId, binding.etRemark.text.toString().checkValue())
        }
    }

    //使用酒币弹窗
    private fun showUseWineCoin() {
        mDataBean?.scoreInfo?.let {
            RetailPopUtils.showUseWineCoin(this, it, useScoreStatus, object : RetailPopUtils.ICallback4UseCoin {
                override fun onClickConfirm(isUse: Boolean) {
                    mDataBean?.let {
                        if (isUse) {
                            //选择了酒币
                            binding.tvUseCoin.text = "-¥${AmountUtil.changeF2YKeepTwo("${it.scoreInfo.scoreDeductPrice}")}"
                            binding.tvUseCoin.setTextColor(ContextCompat.getColor(this@ConfirmNewRetailOrderActivity, R.color.color_D53))
                            binding.tvBottomTotalPrice.text = "${AmountUtil.changeF2YKeepTwo("${it.priceSum.minus(it.scoreInfo.scoreDeductPrice)}")}"
                            useScoreStatus = 0
                        } else {
                            //暂不使用
                            binding.tvUseCoin.setTextColor(ContextCompat.getColor(this@ConfirmNewRetailOrderActivity, R.color.color_333333))
                            binding.tvUseCoin.text = "请选择"
                            binding.tvBottomTotalPrice.text = "${AmountUtil.changeF2YKeepTwo("${it.priceSum}")}"
                            useScoreStatus = 1
                        }
                    }
                }
            })
        }
    }

    //酒币规则
    fun coinRuler() {
        val dictionary = SpUtils.getInstance().loadDictionaryrBean
        val desc = dictionary.getByName_system("currencyRules")
        RetailPopUtils.goodsServerPop(this, null, desc, "酒币规则")
    }

    fun haveAddress(mAddressBean: ReceiveAddressBean?) {
        mAddressBean?.let {
            userAddressId = it.id
            binding.tvProvinceCity.visibility = View.VISIBLE
            binding.tvProvinceCity.text = "${CommonUtil.jsonToBean(it.areaFirst, AddressData::class.java).name.checkValue()}${CommonUtil.jsonToBean(it.areaSecond, AddressData::class.java).name.checkValue()}${CommonUtil.jsonToBean(it.areaThree, AddressData::class.java).name.checkValue()}"
            binding.tvAddressDetail.text = it.address.checkValue()
            binding.tvNamePhone.visibility = View.VISIBLE
            binding.tvNamePhone.text = "${it.name.checkValue()} ${it.phone.checkValue()}"
            binding.llAddress.setOnClickListener {
                if (binding.tvNamePhone.visibility == View.GONE) {
                    ARouterUtils.jump(ActivityRouter.NEW_RETAIL.EDIT_OR_ADD_NEW_ADDRESS)
                } else {
                    val hashMap = HashMap<String, Any>()
                    hashMap[ReceiveAddressActivity.KEY_ADDRESS_ID] = "${mAddressBean.id}"
                    ARouterUtils.jump(ActivityRouter.NEW_RETAIL.RECEIVE_ADDRESS, hashMap)
                }
            }
        }
    }

    fun noAddress() {
        //初始化id
        userAddressId = 0
        binding.tvProvinceCity.visibility = View.GONE
        binding.tvAddressDetail.text = "请填写收货地址"
        binding.tvNamePhone.visibility = View.GONE
        binding.tvAddressDetail.setOnClickListener {
            if (binding.tvNamePhone.visibility == View.GONE) {
                ARouterUtils.jump(ActivityRouter.NEW_RETAIL.EDIT_OR_ADD_NEW_ADDRESS)
            } else {
                //地址列表
                val hashMap = HashMap<String, Any>()
                hashMap[ReceiveAddressActivity.KEY_ADDRESS_ID] = "${userAddressId}"
                ARouterUtils.jump(ActivityRouter.NEW_RETAIL.RECEIVE_ADDRESS, hashMap)
            }
        }
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN) fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_select_address_complete || messageBus.codeType == MessageBus.msgId_new_add_address_success) {
            //选择地址
            val selectAddressBean = messageBus.message as ReceiveAddressBean
            haveAddress(selectAddressBean)
            //设置选中地址
            viewModel.reqSetSelectAddress(selectAddressBean.id)
        } else if (messageBus.codeType == MessageBus.msgId_delete_confirm_order_select_address) {
            //删除选择的地址
            //获取地址
            viewModel.requestAddressList()
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}